<template>
  <div class="container">
    <div class="cheader2">
      <van-icon
          @click="goBack"
          class="chl"
          name="arrow-left"
          color="#000"
          size="20"
      />
      <div class="chtitle">{{ $t('all.chongzhi') }}</div>
      <div class="djbox"></div>
    </div>
    <div class="mbox">
      <!-- 选择货币类型 -->
      <div class="bbtn" @click="showLegalTenderOption = true">
        <img class="bb1" :src="getLegalTenderIconByCode(legalTenderSelection.code)" alt=""/>
        <span class="bb2">{{ legalTenderSelection.code }}</span>
        <van-icon color="#000" name="arrow-down"/>
      </div>

      <!-- 虚拟货币钱包充值 -->
      <div v-show="legalTenderSelection.code === 'USDT'">
        <img class="qcord" :src="qrcodeImg" alt=""/>
        <div class="m1">{{ $t('all.chongzhi_1') }}</div>
        <div class="m2">{{ $t('all.chongzhi_2') }}</div>
        <div class="m3">{{ item.address }}</div>
        <div class="m4" @click="copyDomText(item.address)">{{ $t('all.fuzhidizhi') }}</div>
        <div class="m5">
          {{ $t('all.chongzhi_3') }}<br/>
          {{ $t('all.chongzhi_4') }}{{
            item.minimumRechargeAmount
          }}{{ $t('all.chongzhi_5') }}
        </div>
      </div>

      <!-- QGPay法币充值 -->
      <div class="ibox2" v-show="legalTenderSelection.code !== 'USDT'">
        <div class="ili">
          <div class="ili-1">{{ $t('all.rechargeChannel') }}</div>
          <div class="ili-2">
            <van-field
                @click="showQGPayBusinessOption = true"
                readonly
                v-model="submitForm.businessName"
                :placeholder="$t('all.click2ChoseRechargeChannel')"
            />
          </div>
        </div>
        <div class="ili">
          <div class="ili-1">{{ $t('all.rechargeAmount') }}</div>
          <div class="ili-2">
            <van-field
                v-model="submitForm.amount"
                :placeholder="`${$t('all.amountLimit')}：${qGPayBusinessSelection ? qGPayBusinessSelection.minAmount + ' - ' + qGPayBusinessSelection.maxAmount : $t('all.noRechargeChannelSelected')}`"
            />
          </div>
          <div class="m5">{{ `≈ ${legalTender2USDT} USDT` }}</div>
        </div>
        <div class="ili" style="height: 38px">
          <div class="btn" @click="submitLegalTenderRecharge">
            {{ legalTenderSubmit ? $t('all.processing') : $t('all.tijiao') }}
          </div>
        </div>
      </div>

      <!-- 提示 -->
      <div class="m5" v-show="legalTenderSelection.code !== 'USDT'">
        {{ $t('all.legalTenderRechargeTips1') }}<br/>
        {{ $t('all.legalTenderRechargeTips2') }}<br/>
        {{ $t('all.legalTenderRechargeTips3') }}
      </div>
    </div>

    <!-- 选择货币类型 -->
    <van-dialog
        v-model:show="showLegalTenderOption"
        :title="$t('all.choseLegalTender')"
        :confirmButtonText="$t('all.queren')"
        style="overflow: auto;"
        :closeOnClickOverlay="true"
    >
      <div class="cli" @click="selectLegalTender(i)" v-for="i in legalTenderOption" :key="i.code">
        <img :style="legalTenderSelection.code === 'USDT' ? '' : 'border-radius: 0px'"
             :src="getLegalTenderIconByCode(i.code)" alt=""/>
        <div class="cli2">{{ i.code }}</div>
      </div>
    </van-dialog>

    <!-- 选择业务编码 -->
    <van-dialog
        v-model:show="showQGPayBusinessOption"
        :title="$t('all.choseQGPayChannel')"
        :confirmButtonText="$t('all.queren')"
        style="overflow: auto;"
        :closeOnClickOverlay="true"
    >
      <div class="cli" @click="selectQGPayBusiness(i)" v-for="i in qGPayBusinessOption" :key="i.code">
        <div class="cli2" style="width: 100%;">{{ i.name }}</div>
      </div>
    </van-dialog>
  </div>
</template>

<script setup lang='ts'>
import QRCode from "qrcode";
import {computed, getCurrentInstance, onMounted, reactive, ref} from "vue";
import {useRouter} from "vue-router";
import {useStore} from "@/store";
import {copyDomText, toNonExponential} from "@/utils/common";
import {Toast} from "vant";
import http from "@/utils/http";
import BigNumber from "bignumber.js";
import {
  checkQGPayBusinessAmountLimit,
  getLegalTenderIconByCode,
  legalTenderRechargeLanguage
} from "@/utils/legalTenderRechargeUtils.js";


const {appContext: {config: {globalProperties}}} = getCurrentInstance();
const store = useStore();
const router = useRouter();
const userInfos = computed(() => store.state.users.infos)
const item = computed(() => userInfos.value.rechargeAddress.find((v: any) => v.chain === userInfos.value.envChain))

// 法币相关
const legalTenderUSDT = {
  icon: require('@/assets/images/usdt.png'),
  code: 'USDT',
  rate: '1'
}
const showLegalTenderOption = ref(false)
let legalTenderOption: any = []
const legalTenderSelection = ref(legalTenderUSDT)
const legalTender2USDT = computed(() => {
  if (!submitForm.amount || isNaN(submitForm.amount)) {
    return 0
  }

  const amount = new BigNumber(submitForm.amount);
  let num = amount.div(legalTenderSelection.value.rate)
      .dp(8)
      .toNumber()

  return toNonExponential(num)
})

const showQGPayBusinessOption = ref(false)
let qGPayBusinessOption: any = []
let qGPayBusinessSelection = ref<any>(undefined)
let legalTenderSubmit = ref(false)

const submitForm = reactive({
  legalTenderCode: "",
  amount: 0,
  businessCode: undefined,
  businessName: undefined
});

const goBack = () => {
  router.go(-1);
};
const qrcodeImg = ref("");

onMounted(() => {
  createQRCode();
  legalTenderSelection.value = legalTenderUSDT
  legalTenderSubmit.value = false
  selectLegalTenderOption()
});

// 查询法币列表
const selectLegalTenderOption = () => {
  // 第一个永远使用USDT
  legalTenderOption = [legalTenderUSDT]
  http.get("legal-tender/app/list").then((res: any) => {
    if (res.code === 200) {
      legalTenderOption = legalTenderOption.concat(res.rows)
    }
  });
}

const createQRCode = () => {
  QRCode.toDataURL(item.value.address, {
    version: 7, //版本号
    errorCorrectionLevel: "Q",
    width: 280,
    height: 280,
  }).then((url: string) => {
    qrcodeImg.value = url;
  });
};

// 选择法币
const selectLegalTender = (legalTender: any) => {
  legalTenderSelection.value = legalTender
  if (legalTender.code === 'USDT') {
    showLegalTenderOption.value = false;
    return
  }

  // 如果是法币，根据法币编码查询 代收业务编码
  qGPayBusinessOption = []
  submitForm.businessName = undefined
  qGPayBusinessSelection.value = undefined
  http.get("qg-pay/business/app/list", {
    legalTenderCode: legalTenderSelection.value.code,
    type: '0'
  }).then((res: any) => {
    if (res.code === 200) {
      // 翻译
      for (let i = 0; i < res.rows.length; i++) {
        let item = res.rows[i];
        item.name = legalTenderRechargeLanguage(globalProperties, item.name);
      }

      qGPayBusinessOption = res.rows
    }

    showLegalTenderOption.value = false;
  });
};

// 选择业务编码
const selectQGPayBusiness = (business: any) => {
  qGPayBusinessSelection.value = business
  submitForm.businessName = business.name
  showQGPayBusinessOption.value = false;
};

const submitLegalTenderRecharge = () => {
  if (legalTenderSubmit.value) {
    Toast(globalProperties.$t('all.processing'));
    return;
  }

  if (!submitForm.amount || legalTender2USDT.value < 1) {
    Toast(globalProperties.$t('all.theRechargeAmountIsIncorrect'));
    return;
  }
  if (!qGPayBusinessSelection.value) {
    Toast(globalProperties.$t('all.noRechargeChannelSelected'));
    return;
  }
  if (checkQGPayBusinessAmountLimit(qGPayBusinessSelection, submitForm.amount)) {
    Toast(globalProperties.$t('all.theRechargeAmountIsIncorrect'));
    return;
  }

  legalTenderSubmit.value = true
  http.post("qg-pay/recharge-detail", {
    legalTenderCode: legalTenderSelection.value.code,
    businessCode: qGPayBusinessSelection.value.code,
    amount: submitForm.amount
  }).then((res: any) => {
    if (res.code === 200) {
      resetLegalTenderSubmitForm()
      window.location.assign(res.data)
    } else {
      Toast(globalProperties.$t('all.operationFailed'));
    }
  }).finally(() => {
    legalTenderSubmit.value = false
  })
}

// 重置法币重置表单
const resetLegalTenderSubmitForm = () => {
  submitForm.amount = 0
  submitForm.businessName = undefined
  submitForm.businessCode = undefined
}
</script>

<style lang="scss" scoped>
.cheader2 {
  z-index: 1001;
  width: 100%;
  height: 45px;
  background-color: #fff;
  font-size: 16px;
  color: #000;
  position: fixed;
  top: 0;
  left: 0;

  .chl {
    position: absolute;
    left: 16px;
    top: 50%;
    text-align: center;
    transform: translateY(-50%);
  }

  .chtitle {
    position: absolute;
    left: 50%;
    top: 50%;
    text-align: center;
    transform: translate(-50%, -50%);
  }

  .djbox {
    position: absolute;
    right: 16px;
    top: 50%;
    transform: translateY(-50%);
    display: flex;
    align-items: center;

    img {
      width: 16px;
      margin-right: 4px;
    }

    div {
      font-size: 13px;
      color: #878b97;
    }
  }
}

.mbox {
  margin-top: 45px;
  padding: 10px 16px;

  .bbtn {
    width: 40vw;
    height: 40px;
    border-radius: 20px;
    background: rgba($color: #fff, $alpha: 1);
    display: flex;
    align-items: center;
    margin: 10px auto 0px;

    .bb1 {
      width: 20px;
      margin: 0 10px 0 20px;
    }

    .bb2 {
      color: #000;
      font-size: 13px;
      margin-right: 14px;
    }
  }

  .qcord {
    width: 180px;
    height: 180px;
    margin: 10px auto 20px;
    display: block;
    border-radius: 2px;
  }

  .m1 {
    font-size: 13px;
    color: #333;
    text-align: center;
    margin: 0px 0 30px;
  }

  .m2 {
    font-size: 13px;
    color: #878b97;
    text-align: center;
    margin: 0 0 12px;
  }

  .m3 {
    font-size: 14px;
    color: #333;
    text-align: center;
  }

  .m4 {
    height: 36px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 14px;
    color: #fff;
    background-image: linear-gradient(to bottom right, #36b4ea, #0996d3);
    border-radius: 3px;
    margin: 20px 0;
  }

  .m5 {
    font-size: 12px;
    color: #878b97;
    line-height: 18px;
  }
}

.cli {
  display: flex;
  height: 60px;
  align-items: center;
  background: #f2f2f2;
  border-radius: 4px;
  margin: 10px 20px 0px;

  &:last-child {
    margin-bottom: 10px;
  }

  img {
    width: 34px;
    height: 34px;
    border-radius: 50%;
    margin-right: 20px;
    margin-left: 40px;
  }

  .cli2 {
    text-align: center;
    font-size: 15px;
  }
}

.ibox2 {
  margin: 10px 20px;

  .ili {
    display: flex;
    flex-direction: column;
    margin-bottom: 14px;

    .ili-1 {
      font-size: 12px;
      color: #000;
      margin-bottom: 10px;
    }

    .ili-2 {
      background-color: #2d2f3b;
      border-radius: 4px;
      // height: 38px;
      position: relative;

      .xxx {
        position: absolute;
        right: 14px;
        top: 50%;
        transform: translateY(-50%);
        color: #878b97;
        font-size: 13px;
        z-index: 1001;

        span {
          margin-left: 6px;
          color: #36b4ea;
        }
      }
    }
  }

  .m5 {
    font-size: 12px;
    color: #878b97;
    line-height: 18px;
  }
}

.btn {
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  color: #fff;
  background-image: linear-gradient(to bottom right, #36b4ea, #0996d3);
  border-radius: 3px;
  width: calc(100% - 40px);
  position: fixed;
  left: 50%;
  transform: translateX(-50%);
}
</style>
